package com.hongye.app.model;

import java.util.List;

import com.alibaba.druid.util.StringUtils;
import com.hongye.util.Utils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;

public class ViewDetailModel extends Model<ViewDetailModel>{

	private static final long serialVersionUID = 1L;
	public static final ViewDetailModel dao = new ViewDetailModel();
	
	
	/**
	 * 添加商品访问量（同一IP地址或用户为一条数据）
	 * @author lifuqiang
	 * 2017-2-27
	 * @param fromphone：浏览人的手机号
	 * @param fromip：浏览人的ip地址
	 * @param tophone：被浏览人的手机号
	 * @param goodsid：被浏览商品的id
	 * @return
	 */
	public static void addViewDetail(String fromphone, String fromip, int goodsid){
		if(!StringUtils.isEmpty(fromphone) && !StringUtils.isEmpty(fromip)){
			String userid = GoodsModel.dao.findById(goodsid).getStr("seller_id");
			String tophone = UserAppModel.dao.findById(userid).getStr("phone");
			if(StringUtils.isEmpty(fromphone)){
				if(isExistByFromIP(fromip, goodsid)){
					new ViewDetailModel().set("fromip", fromip).set("tophone", tophone).set("togoodsid", goodsid).set("ctime", Utils.getDate()).save();
				}
			}else{
				if(!fromphone.equals(tophone)){
					if(isExistByFromPhone(fromphone, goodsid)){
						new ViewDetailModel().set("fromphone", fromphone).set("tophone", tophone).set("togoodsid", goodsid).set("ctime", Utils.getDate()).save();
					}
				}
			}
		}
	}
	
	/**
	 * 判断是否浏览过
	 * @author lifuqiang
	 * 2017-2-27
	 * @param fromphone 浏览人手机号
	 * @param goodsid 被浏览商品id
	 * @return
	 */
	public static boolean isExistByFromPhone(String fromphone, int goodsid){
		String sql = "select * from viewdetail where fromphone = '"+fromphone+"' and togoodsid = '"+goodsid+"'";
		List<ViewDetailModel> viewmodel = dao.find(sql);
		boolean boo = false;
		if(viewmodel.size()<1){
			boo = true;
		}
		return boo;
	}
	
	/**
	 * 判断是否浏览过
	 * @author liushaomin
	 * 2017年2月28日
	 * @param fromip 浏览人ip
	 * @param goodsid 被浏览商品id
	 * @return
	 */
	public static boolean isExistByFromIP(String fromip, int goodsid){
		String sql = "select * from viewdetail where fromip = '"+fromip+"' and togoodsid = '"+goodsid+"'";
		List<ViewDetailModel> viewmodel = dao.find(sql);
		boolean boo = false;
		if(viewmodel.size()<1){
			boo = true;
		}
		return boo;
	}

	/**
	 * 获取店铺的总访问量
	 * @author liushaomin
	 * 2017年2月28日
	 * @param tophone
	 * @return
	 */
	public static Long getLook_Num(String tophone) {
		String sql = "select count(1) from viewdetail where tophone =" + tophone + "";
		return getLook(sql);
	}
	
	/**
	 * 获取店铺访问量
	 * @author liushaomin
	 * 2017年6月12日
	 * @param strsql
	 * @return
	 */
	public static Long getLook(String strsql) {
		return Db.queryLong(strsql);
	}
}
